Ext.define('Lms.rms.SystemInfoDialog',{
	id : 'SystemInfoDialog',
	
	openWindow : function(config) {
		Ext.apply(this, config);
		this.isEditableMode = false; 
		var title = LocaleUtil.getMessage('rms.label.system');
		if(typeof(config) != 'undefined'){
			title += LocaleUtil.getMessage('rms.label.detail');
			this.isEditableMode = true;
		}else{
			title += LocaleUtil.getMessage('reg');
		}
		this.dialog = Common.openDialog(title, 600, 600, [{
			text : (this.isEditableMode)?LocaleUtil.getMessage('update'):LocaleUtil.getMessage('reg'),
			scope : this,
			handler : function(){
				if(!this.form.isValid()) return;
				Common.confirm(LocaleUtil.getMessage('confirm'),LocaleUtil.getMessage('rms.msg.doYouWantToSave'),function(btn){
					if(btn == 'yes'){
						this.onSubmit();
					}
				},this);
			}
		},{
			text : LocaleUtil.getMessage('close'),
			cls : 'blue_button',
			scope : this,
			handler : this.onClose
		}]);
		this.dialog.resizable = true;
//		this.dialog.iconCls = 'detail_search';
		this.dialog.add(Ext.widget('panel',{
			xtype : 'panel',
			layout : 'border',
			frame : false,
			border : false,
			items : [
			    this.getForm(),{
			    	xtype : 'panel',
			    	region : 'center',
			    	layout : 'border',
			    	border : false,
			    	items : [
			    	    this.getHardwareGrid(),
			    	    this.getSoftwareGrid()
			    	]
			    }
			    
			]
		}));
		this.dialog.show();
		if(this.isEditableMode){
			this.getData();
		}
	},
	
	onClose : function(){
		this.dialog.close();
		if(this.refreshStore){
			this.refreshStore.reload();
		}else{
			Ext.getCmp('SystemMgmPanel').getStore().reload();
		}
	},
	
	onSubmit : function(){
		var url;
		if(this.isEditableMode){
			//수정 logic
			url = 'pc/update.do';
		}else{
			//등록 url
			url = 'pc/create.do';
		}
		var hardwareGridStore = this.hardwareGrid.getStore();
		var softwareGridStore = this.softwareGrid.getStore();
		var id = this.id;
		var i = 0;
		var param = '?';
 	    hardwareGridStore.each(function(record){
 	    	
 	    	param += 'itemVOs['+i+'].parentId='+id + '&' +
 	    	'itemVOs['+i+'].hwSwId='+record.get('id')+'&' +
 	    	'itemVOs['+i+'].inventory='+record.get('inventory')+'&' +
 	    	'itemVOs['+i+'].ip='+(!record.get('ip')?'':record.get('ip'))+'&' +
 	    	'itemVOs['+i+'].sepType='+'HW&';
 	    	i++;
 	    }); 
 	    softwareGridStore.each(function(record){
 	    	param += 'itemVOs['+i+'].parentId='+id + '&' +
 	    	'itemVOs['+i+'].hwSwId='+record.get('id')+'&' +
 	    	'itemVOs['+i+'].sepType='+'SW&';		
 	    	i++;
 	    });
		this.form.getForm().submit({
			url : url + param,
			scope : this,
			success : this.onClose,
			failure : Common.failureMessageSubmit
		}); 	    
 	    
	},
	
	getData : function(){
		this.form.load({
			url : 'pc/findInfo.do',
			params : {
				id : this.id
			}
		});
		if(this.isEditableMode){
			this.hardwareGrid.getStore().load({
				params : {
					parentId : this.id,
					sepType : 'HW'
				}
			});
			this.softwareGrid.getStore().load({
				params : {
					parentId : this.id,
					sepType : 'SW'
				}
			});
		}
	},
	
	getForm : function(){
		this.form = Ext.widget('form',{
			frame : false,
		    border : false,
		    region : 'north',
		    bodyPadding: '5 5 0',
	        defaults: {anchor: '100%'},
	        defaultType: 'textfield',
	        fieldDefaults: {
	        	labelAlign : 'right',
                labelWidth: 120,
                msgTarget : 'side'
            },
	        items :[{
	        		xtype : 'hiddenfield',
	        		name : 'id'
	        	},{
	        		xtype : 'combobox',
	        		store : new Ext.data.JsonStore({
	        			autoLoad:true,
	        			fields: ['id','name'],
	        			proxy : {
	        				url : 'zone/list.do',
	        				type : 'ajax'
	        			}	        			
	        		}),
	        		name: 'zone',
	        		fieldLabel: LocaleUtil.getMessage('rms.label.zone'),
	        		valueField: 'id',
    	          	displayField:'name',
    	          	forceSelection: true,
    	          	editable: false,
    	          	allowBlank : false
                },{            	
                    fieldLabel: LocaleUtil.getMessage('rms.label.systemName'),
                    name: 'name',
                    allowBlank : false,
                    readOnly : false
                },{
                    fieldLabel: LocaleUtil.getMessage('rms.label.ipAddress'),
                    name: 'ip',
                    allowBlank : false,
                    readOnly : false,
                    listeners : {
                    	scope : this,
                    	keypress : function(txtField, e, eOpts){
    						if(e.getKey() == 13){
    							this.getMacAddress();
    						}
    					},
    					blur : this.getMacAddress
                    }
                },{
//                	xtype : 'displayfield',
                    fieldLabel: LocaleUtil.getMessage('rms.label.macAddress'),
                    name: 'macAddress',
                    allowBlank : false,
                    emptyText : LocaleUtil.getMessage('rms.msg.ipInputWillByRegAutomatically'),
                    blankText : LocaleUtil.getMessage('rms.msg.ipInputWillByRegAutomatically'),
                    readOnly : true           
                },{
                    fieldLabel: LocaleUtil.getMessage('rms.label.systemDescription'),
                    name: 'description',
                    readOnly : false
                },{
                	fieldLabel: LocaleUtil.getMessage('rms.label.useCMS'),
                    xtype: 'radiogroup',
                    anchor: 'none',
                    layout: {
                        autoFlex: false
                    },
                    defaults: {
                        name: 'cmsStatus',
                        margin: '0 15 0 0'
                    },
                    items: [{
                        inputValue: '1',
                        boxLabel: LocaleUtil.getMessage('rms.label.use'),
                        checked: true
                    },{
                        inputValue: '0',
                        boxLabel: LocaleUtil.getMessage('rms.label.notUse')
                    }]
                }
            ]      
		});
		
		return this.form;
	},
	
	getMacAddress : function(){
		var ip = this.form.getForm().findField('ip').getValue();
		Ext.Ajax.request({
	        url:'if/getMacAddress.do',
	        params: {
	        	ip : ip
	        },
	        scope : this,
	        success : function(result, request){
	        	var macAddress = result.responseText;
	        	//Mac Address가 없거나 ERR이면 field에 업데이트 하지 않는다.
	        	if(macAddress == 'ERR'){
	        		Common.alert(LocaleUtil.getMessage('confirm'),LocaleUtil.getMessage('rms.msg.notFoundMacAddress'));
	        	}else{
	        		this.form.getForm().findField('macAddress').setValue(macAddress);
	        	}
	        },
	        failure: Common.failureMessage
	    });
	},
	
	getHardwareGrid : function(){
		var store = Ext.create('Ext.data.Store', {
		    fields: ['id','name','ip','inventory','type'],
		    autoLoad : false,
		    proxy : {
				type : 'ajax',
				url : 'pc/findPcItemByType.do',
				actionMethods : {
					read : 'POST'					
				},
				reader : {
					type : 'json'
				}
			}
		});
		this.hardwareGrid = Ext.create('Ext.grid.Panel', {
			region : 'center',
		    store: store,
		    width : '50%',
			columnLines: true,
			viewConfig : Common.viewConfig(true),
			selType: 'checkboxmodel',
			plugins : [Ext.create('Ext.grid.plugin.CellEditing')],
		    columns: [
		        {text : LocaleUtil.getMessage('rms.label.equivName'),dataIndex : 'name',  	flex: 1 },
		        {text : LocaleUtil.getMessage('rms.label.inventory'),dataIndex : 'inventory', width : 50, editor : {xtype : 'numberfield',minValue: 1}},
		        {text : LocaleUtil.getMessage('rms.label.ipAddress'),dataIndex : 'ip', width : 100, editor : {xtype : 'textfield'}}
		    ],
		    tbar : [{
		    	xtype : 'label',
		    	text : LocaleUtil.getMessage('rms.label.etcEquiv')
		    },'->',{
		    	text : LocaleUtil.getMessage('add'),
		    	iconCls : 'add',
		    	scope : this,
		    	handler : this.openAddHardwareDialog
		    },{
		    	text : LocaleUtil.getMessage('del'),
		    	iconCls : 'delete',
		    	scope : this,
		    	handler : function(){
		    		var selectedRecords = this.hardwareGrid.getSelectionModel().getSelection();
		    		if(selectedRecords.length == 0) return;
		    		this.hardwareGrid.getStore().remove(selectedRecords);
		    	}
		    }]
		});
		this.hardwareGrid.on('beforeedit',function(editor, e, eOpts){
			//PROJECT만 IP입력가능하게
			if(e.record.get('type') != 'PROJECTOR'){
				return false;
			}
		},this);
		return this.hardwareGrid;
	},
	
	openAddHardwareDialog : function(){
		var hardwareGridStore = this.hardwareGrid.getStore();
		var store = Ext.create('Ext.data.Store',{
			fields: [
		         'id','name','inventory','type'
		    ],
			sortInfo: {
		        field    : 'name',
		        direction: 'ASC'
		    },
			autoLoad: false,
			proxy : {
				type : 'ajax',
				actionMethods : {
					read : 'POST'					
				},
				url : 'hardware/list.do',
				reader : {
					type : 'json'
				}
			},
			filters : [
	           function(record){
	        	   for(var i=0; i < hardwareGridStore.getCount(); i++){
	        		   if(record.get('name') == hardwareGridStore.getAt(i).get('name')){
	        			   return false;
	        		   }
	        	   }
	        	   return true;
	           }
			]
		});
		this.addHardwareDialog = Common.openDialog(LocaleUtil.getMessage('rms.label.etcEquiv')+ LocaleUtil.getMessage('add'), 300, 300, [{
			text : LocaleUtil.getMessage('add'),
			scope :this,
			handler : function(){
				var grid = this.addHardwareDialog.getComponent(0);
				var records = grid.getSelectionModel().getSelection();
				this.hardwareGrid.getStore().add(records);
				this.addHardwareDialog.close();
			}
		},{
			text : LocaleUtil.getMessage('close'),
			scope : this,
			handler : function(){
				this.addHardwareDialog.close();
			}
		}]);
		this.addHardwareDialog.add({
			xtype : 'grid',
			store : store,
			selType: 'checkboxmodel',
			viewConfig : Common.viewConfig(true),
			columnLines: true,
			columns : [
			    {text : LocaleUtil.getMessage('rms.label.etcEquiv'),dataIndex : 'name', flex:1},
			]
		});
		
		this.addHardwareDialog.show(store.load());
	},
	
	getSoftwareGrid : function(){
		var store = Ext.create('Ext.data.Store', {
		    fields:['id', 'name'],
		    autoLoad : false,
		    proxy : {
				type : 'ajax',
				url : 'pc/findPcItemByType.do',
				reader : {
					type : 'json'
				}
			}
		});
		this.softwareGrid = Ext.create('Ext.grid.Panel', {
			region : 'east',
			width : '50%',
		    store: store,
			columnLines: true,
			viewConfig : Common.viewConfig(true),
			selType: 'checkboxmodel',
		    columns: [
		        {text : LocaleUtil.getMessage('rms.label.swName'),dataIndex : 'name',  flex: 1 }
		    ],
		    tbar : [{
		    	xtype : 'label',
		    	text : LocaleUtil.getMessage('rms.label.software')
		    },'->',{
		    	text : LocaleUtil.getMessage('add'),
		    	iconCls : 'add',
		    	scope : this,
		    	handler : this.openAddSoftwareDialog
		    },{
		    	text : LocaleUtil.getMessage('del'),
		    	iconCls : 'delete',
		    	scope : this,
		    	handler : function(){
		    		var selectedRecords = this.softwareGrid.getSelectionModel().getSelection();
		    		if(selectedRecords.length == 0) return;
		    		this.softwareGrid.getStore().remove(selectedRecords);
		    	}
		    }]
		});
		return this.softwareGrid;
	},
	
	openAddSoftwareDialog : function(){
		var softwareGridStore = this.softwareGrid.getStore();
		var store = Ext.create('Ext.data.Store',{
			fields: [
		         'id','name'
		    ],
			sortInfo: {
		        field    : 'name',
		        direction: 'ASC'
		    },
			autoLoad: false,
			proxy : {
				type : 'ajax',
				url : 'software/list.do',
				reader : {
					type : 'json'
				}
			},
			filters : [
	           function(record){
	        	   for(var i=0; i < softwareGridStore.getCount(); i++){
	        		   if(record.get('name') == softwareGridStore.getAt(i).get('name')){
	        			   return false;
	        		   }
	        	   }
	        	   return true;
	           }
			]
		});
		this.addSoftwareDialog = Common.openDialog(LocaleUtil.getMessage('rms.label.software')+ LocaleUtil.getMessage('add'), 300, 300, [{
			text : LocaleUtil.getMessage('add'),
			scope :this,
			handler : function(){
				var grid = this.addSoftwareDialog.getComponent(0);
				var records = grid.getSelectionModel().getSelection();
				this.softwareGrid.getStore().add(records);
				this.addSoftwareDialog.close();
			}
		},{
			text : LocaleUtil.getMessage('close'),
			scope : this,
			handler : function(){
				this.addSoftwareDialog.close();
			}
		}]);
		this.addSoftwareDialog.add({
			xtype : 'grid',
			store : store,
			selType: 'checkboxmodel',
			viewConfig : Common.viewConfig(true),
			columnLines: true,
			columns : [
			    {text : 'SW Name',dataIndex : 'name', flex:1},
			]
		});
		this.addSoftwareDialog.show(store.load());
	}
});